package cn.zhxu.toys.msg;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

import java.util.Arrays;
import java.util.Map;
import java.util.Objects;

/**
 * 阿里短信发送器
 * @author Troy.Zhou
 * @since 1.0.2
 */
public class AliyunMsgSender extends AbstractMsgSender {

	public static String DEFAULT_ENDPOINT = "dysmsapi.aliyuncs.com";

	private String endpoint = DEFAULT_ENDPOINT;
	
	private String accessKeyId;
	private String accessKeySecret;
	private String signName;

	public AliyunMsgSender() {
	}

	public AliyunMsgSender(String name) {
		super(name);
	}

	@Override
	public void init(Map<String, String> params) {
		String endpoint = params.get("endpoint");
		String accessKeyId = params.get("accessKeyId");
		String accessKeySecret = params.get("accessKeySecret");
		String signName = params.get("signName");
		if (accessKeyId == null) {
			throw new MsgSenderInitException("缺少参数：appId");
		}
		if (accessKeySecret == null) {
			throw new MsgSenderInitException("缺少参数：accessKeySecret");
		}
		if (signName == null) {
			throw new MsgSenderInitException("缺少参数：signName");
		}
		if (endpoint != null) {
			this.endpoint = endpoint;
		}
		this.accessKeyId = accessKeyId;
		this.accessKeySecret = accessKeySecret;
		this.signName = signName;
	}

	private Client client;

	protected Client client() {
		if (client != null) {
			return client;
		}
		Config config = new Config()
				.setEndpoint(Objects.requireNonNull(endpoint))
				.setAccessKeyId(Objects.requireNonNull(accessKeyId))
				.setAccessKeySecret(Objects.requireNonNull(accessKeySecret));
		try {
			client = new Client(config);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return client;
	}

	@Override
	public SendResult send(String phone, MsgTemplate template, String... tmplArgs) {
		SendSmsRequest request = new SendSmsRequest();
		request.setSignName(Objects.requireNonNull(signName));
		request.setPhoneNumbers(phone);
		request.setTemplateCode(template.getTmplValue());
		String[] argNames = template.getTmplArgs();
		StringBuilder sb = new StringBuilder();
		if (tmplArgs != null) {
			if (tmplArgs.length > 0 && (argNames == null || argNames.length < tmplArgs.length)) {
				throw new RuntimeException("MsgTemplate tmplArgs not match: " + Arrays.toString(argNames) + " to " + Arrays.toString(tmplArgs));
			}
			sb.append("{");
			for (int index = 0; index < tmplArgs.length; index ++) {
				sb.append("\"")
						.append(argNames[index])
						.append("\":")
						.append("\"")
						.append(tmplArgs[index])
						.append("\"");
				if (index < tmplArgs.length - 1) {
					sb.append(",");
				}
			}
			sb.append("}");
		}
		request.setTemplateParam(sb.toString());
		SendSmsResponse response;
		try {
			response = client().sendSms(request);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		boolean success = response.statusCode == 200 && "OK".equals(response.body.code);
		return new SendResult(success, response.body.message);
	}

	public String getEndpoint() {
		return endpoint;
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	public String getAccessKeyId() {
		return accessKeyId;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public String getAccessKeySecret() {
		return accessKeySecret;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public String getSignName() {
		return signName;
	}

	public void setSignName(String signName) {
		this.signName = signName;
	}

}
